﻿using System;
using System.ComponentModel;

namespace Td.Additional
{
    /// <summary>
    /// Helper methods for enumerations.
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// Gets the enum description from an (optional) description attribute.
        /// </summary>
        /// <param name="enumValue">The enum value.</param>
        /// <returns>The description from a found description attribute, the enumeration value name or <c>null</c>, if value is not defined in the enumeration.</returns>
        public static String GetEnumDescription(Enum enumValue)
        {
            var enumType = enumValue.GetType();
            if (!Enum.IsDefined(enumType, enumValue))
                return null;//oder: Fehlermeldung
            String result = null;
            var enumTypeInfo = enumType.GetField(enumValue.ToString());
            var attributes = (DescriptionAttribute[])enumTypeInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
                result = attributes[0].Description;
            else
                result = enumValue.ToString();
            return result;
        }
    }
}